import json

import requests
from flask import *
from pymysql import Connect
from flask_cors import CORS
from Flask.log_util import logger

app = Flask(__name__)
CORS(app)
# 声明蓝图
bookBP = Blueprint(name="book", import_name=__name__)
# 连接数据库
db_connect = Connect(host='localhost', port=3306, user="root", password="921060", database="bms", charset="utf8")


# 蓝图管理接口
# 首页接口
@bookBP.route("/")
def index():
    return render_template("index.html")


@bookBP.route("/list", methods=["GET", "POST"])
def list():
    curser = db_connect.cursor()
    sql_str = """select * from book;"""
    curser.execute(sql_str)
    data = curser.fetchall()
    datas = []
    for item in data:
        book_list = {
            "bid": item[0],
            "name": item[1],
            "price": item[2],
            "summary": item[3],
            "quantity": item[4]
        }
        datas.append(book_list)
    logger.info(f"书本列表{datas}")
    curser.close()
    # return json.dumps(datas, ensure_ascii=False)
    return datas


@bookBP.route("/add", methods=["GET", "POST"])
def add():
    if request.method == "GET":
        return render_template("add.html")
    else:
        name = request.values.get("name")
        price = request.values.get("price")
        summary = request.values.get("summary")
        quantity = request.values.get("quantity")
        curser = db_connect.cursor()
        sql_str = """insert into book (name,price,summary,quantity) values (%s,%s,%s,%s)"""
        curser.execute(sql_str, (name, price, summary, quantity))
        db_connect.commit()
        curser.execute("""select * from book order by bid desc limit 1""")
        logger.info(f"添加数据：{curser.fetchall()}")
        curser.close()
        return redirect("/")


@bookBP.route("/change/<bid>", methods=["GET", "POST"])
def change(bid):
    if request.method == "GET":
        return render_template("change.html")
    else:
        # bid = request.values.get("bid")
        # logger.info(bid)
        name = request.values.get("name")
        price = request.values.get("price")
        summary = request.values.get("summary")
        quantity = request.values.get("quantity")
        curser = db_connect.cursor()
        sql_str = """update book set name=%s,price=%s,summary=%s,quantity=%s where bid=%s"""
        curser.execute(sql_str, (name, price, summary, quantity, bid))
        db_connect.commit()
        curser.execute(f"select * from book where bid={bid}")
        logger.info(f"修改数据：{curser.fetchall()}")
        curser.close()
        return redirect("/")


@bookBP.route("/changedata/<bid>", methods=["GET"])
def changedata(bid):
    curser = db_connect.cursor()
    sql_str = """select * from book where bid=%s"""
    curser.execute(sql_str, (bid,))
    item = curser.fetchone()
    data = {
        "bid": item[0],
        "name": item[1],
        "price": item[2],
        "summary": item[3],
        "quantity": item[4]
    }
    logger.info(f"修改数据回回显{data}")
    curser.close()
    return data


@bookBP.route("/delete/<bid>", methods=["GET"])
def delete(bid):
    curser = db_connect.cursor()
    sql_str = """delete from book where bid=%s"""
    curser.execute(sql_str, (bid,))
    db_connect.commit()
    curser.close()
    return redirect("/")


@bookBP.route("/search", methods=["GET", "POST"])
def search():
    curser = db_connect.cursor()
    key = request.values.get("key")
    logger.info(key)
    if key is None:
        sql_str = "select * from book"
        curser.execute(sql_str)
        data = curser.fetchall()
        datas = []
        for item in data:
            book_list = {
                "bid": item[0],
                "name": item[1],
                "price": item[2],
                "summary": item[3],
                "quantity": item[4]
            }
            datas.append(book_list)
            curser.close()
        logger.info(f"查询到的内容为：{datas}")
        return datas
    else:
        # 定义模糊查询sql语句
        sql_str = f"select * from book where name like '%{key}%' or summary like '%{key}%'"
        curser.execute(sql_str)
        data = curser.fetchall()
        datas = []
        for item in data:
            book_list = {
                "bid": item[0],
                "name": item[1],
                "price": item[2],
                "summary": item[3],
                "quantity": item[4]
            }
            datas.append(book_list)
        curser.close()
        logger.info(f"查询到的内容为：{datas}")
        return datas


if __name__ == '__main__':
    app.register_blueprint(bookBP)
    app.run(debug=True)
